﻿use actix_web::http::header::LOCATION;
use actix_web::HttpResponse;
use anyhow::Context;
use sqlx::PgPool;
use std::fmt::{Debug, Display};
use uuid::Uuid;

// 返回一个不透明的 500 错误，同时保留错误的根本原因，以便记录
pub fn e500<T>(e: T) -> actix_web::Error
where
    T: Debug + Display + 'static,
{
    actix_web::error::ErrorInternalServerError(e)
}

pub fn see_other(location: &str) -> HttpResponse {
    HttpResponse::SeeOther()
        .insert_header((LOCATION, location))
        .finish()
}

#[tracing::instrument(name = "Get username", skip(pool))]
pub async fn get_username(user_id: Uuid, pool: &PgPool) -> Result<String, anyhow::Error> {
    let row = sqlx::query!(r#"SELECT username FROM users WHERE user_id = $1"#, user_id,)
        .fetch_one(pool)
        .await
        .context("Failed to perform a query to retrive a username.")?;
    Ok(row.username)
}

pub fn e400<T>(e: T) -> actix_web::Error
where
    T: std::fmt::Debug + std::fmt::Display + 'static,
{
    actix_web::error::ErrorBadRequest(e)
}
